package admin_login_service

import (
	"errors"
	admin_login_types "oc_saas/internal/app/api/admin/login/types"
	"oc_saas/internal/model/share"
	oc_types "oc_saas/internal/types"
	"oc_saas/internal/types/api"
)

type Login struct {
	api.Service
}

func (s *Login) Login(req *admin_login_types.LoginBody, res *admin_login_types.LoginRes) {
	var user *share.User
	err := s.Orm.Model(share.User{}).Select(`
		id,
		only_id,
		status
	`).Where("username = ? AND password = ?", req.Username, req.Password).Scan(&user).Error
	if err != nil {
		panic(err)
	} else if user == nil {
		panic(errors.New(oc_types.USER_NOT_EXIST))
	}
	// 判断是否封禁
	if user.Status == 0 {
		panic(errors.New(oc_types.USER_BANED))
	}
	// 搜出用户关联的角色、所属租户、所属应用信息
	var resBody *admin_login_types.LoginSearchUser
	err = s.Orm.
		Model(&share.RoleUser{}).
		Where("user_id = ?", user.ID).
		Select(`
			r.db_id,
			r.jwt_expire,
			a.name,
			t.db_name,
			t.domain
		`).
		Joins("LEFT JOIN oc_role as r on r.id = oc_role_user.role_id").
		Joins("LEFT JOIN oc_tenancy_db as t on t.`id` = r.`db_id`").
		Joins("LEFT JOIN oc_application as a on t.`application_id` = a.id").Scan(&resBody).Error
	if err != nil {
		panic(&oc_types.CustomError{
			Msg:   oc_types.FORM_ERR,
			Error: err.Error(),
		})
	}
	res.Token = admin_login_types.GenTokenString(resBody, user.OnlyID.String())
}
